<template>
  <div class="tree-container">
    <px-tree
      ref="treeRef"
      :data="treeData"
      node-key="id"
      highlight-current
      default-expand-all
      :allow-drag="handleAllowDrag"
      :current-node-key="currentNode"
      :expand-on-click-node="false"
      draggable
      :allow-drop="allowDrop"
      @node-click="nodeClick"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node show-hide">
          <span class="text" :title="node.label" :style="{ maxWidth: node.level === 5 ? '45px' : '100px' }">
            <Folder class="folder-icon" />
            {{ node.label }}
          </span>
          <span class="tree-icon-container" style="display: none">
            <px-tooltip content="编辑" placement="top">
              <a @click.stop="editNode(data)"> <TreeEdit class="tree-icon" /> </a>
            </px-tooltip>
            <span v-if="node.level !== 1">
              <px-tooltip content="删除" placement="top">
                <a @click.stop="deleteNode(data)"> <TreeDelete class="tree-icon" /> </a>
              </px-tooltip>
            </span>
            <px-tooltip content="新增" placement="top">
              <a @click.stop="addNode(data, node)"> <TreeAdd class="tree-icon" /> </a>
            </px-tooltip>
          </span>
        </span>
      </template>
    </px-tree>

    <px-dialog v-model="dialogVisible" :title="dialogTitle" width="400px" :before-close="cancel">
      <div class="move-tree-container">
        <px-input v-model="folderVal" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="cancel">取消</px-button>
          <px-button type="primary" @click="confirm">确定</px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, watch, toRefs, onUnmounted } from "vue";
import TreeAdd from "@/assets/svg/knowledge/tree_add.svg?component";
import TreeEdit from "@/assets/svg/knowledge/tree_edit.svg?component";
import TreeDelete from "@/assets/svg/knowledge/tree_delete.svg?component";
import Folder from "@/assets/svg/knowledge/folder.svg?component";
import { PxMessageBox, PxMessage } from "px-ui";
import { moveFolderAPI } from "@/api/knowledge/documentManage";
import { debounce } from "@pureadmin/utils";

const emits = defineEmits(["editNode", "deleteNode", "addNode", "nodeClick", "nodeDrag"]);
const props = defineProps({
  treeData: {
    type: Array,
    default() {
      return [];
    }
  }
});

const treeRef = ref();
const currentNode = ref();

const state = reactive({
  dialogVisible: false,
  dialogTitle: "",
  folderVal: ""
});
const { dialogVisible, dialogTitle, folderVal } = toRefs(state);

// watch(
//   () => props.treeData,
//   () => {
//     nextTick(() => {
//       setCurrentKey(props.treeData[0]?.id);
//     });
//   },
//   { immediate: true, deep: true }
// );

// 获取所有父级节点
const getAllParentNode = node => {
  if (node) {
    let nodeParentAll = [];
    // 节点的第一个父级
    let parentNode = node.parent;
    // level为节点的层级 level=1 为顶级节点
    for (let i = 0; i < node.level; i++) {
      if (parentNode.level > 0) {
        // 将所有父级节点放入集合中
        nodeParentAll.push(parentNode);
      }
      // 继续获取父级节点的父级节点
      parentNode = parentNode.parent;
    }

    if (nodeParentAll.length > 1) {
      // 如果集合长度>1 则将数组进行倒叙.reverse() 其是就是将所有节点按照 从 顶级节点 依次往下排
      nodeParentAll.reverse();
    }
    return nodeParentAll;
  }
};

// 获取所有父节点id
const getAllParentNodeId = nodeData => {
  const parentNodes = [];
  const findParent = node => {
    let pid = treeRef.value.getNode(node).parent.data.id;
    if (pid !== 0) {
      parentNodes.push(pid);
      findParent(treeRef.value.getNode(node).parent.data);
    }
  };
  findParent(nodeData);
  return parentNodes;
};

const getParentId = node => {
  return treeRef.value.getNode(node).parent.data.id;
};

// 根节点禁止拖拽
const handleAllowDrag = node => {
  return node.level !== 1;
};

// 设置选中节点
const setCurrentKey = id => {
  nextTick(() => {
    currentNode.value = id;
    treeRef.value.setCurrentKey([id]);
  });
};

// 编辑节点
const editNode = data => {
  state.dialogVisible = true;
  state.dialogTitle = "修改文件夹";
  state.folderVal = data.name;
  setCurrentKey(data.id);
};

// 删除节点
const deleteNode = data => {
  PxMessageBox.confirm(`是否确认删除文件夹"${data.name}"？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      emits("deleteNode", data.id);
    })
    .catch(() => {});
};

// 添加节点
const addNode = (data, node) => {
  setCurrentKey(data.id);
  emits("nodeClick", data, node);
  state.dialogVisible = true;
  state.dialogTitle = "新建文件夹";
};

const cancel = () => {
  state.dialogVisible = false;
  state.dialogTitle = "";
  state.folderVal = "";
};

const confirm = () => {
  if (state.dialogTitle === "新建文件夹") {
    emits("addNode", currentNode.value, state.folderVal);
  } else {
    emits("editNode", currentNode.value, state.folderVal);
  }
  cancel();
};

// 点击节点
const nodeClick = (data, node, obj) => {
  currentNode.value = data.id;
  emits("nodeClick", data, node, obj);
};

// const allowDrop = () => {
//   return true;
// };

const allowDrop = debounce(async (draggingNode, dropNode, type) => {
  try {
    const params = {
      id: [draggingNode.data.id],
      targetFolderId: dropNode.data.id
    };
    let res = await moveFolderAPI(params);
    if (res === "不允许操作") {
      PxMessage.error("不允许移动");
      return false;
    } else {
      PxMessage.success("移动成功");
      emits("nodeDrag");
      return true;
    }
  } catch (error) {
    return false;
  }
}, 300);

defineExpose({
  getAllParentNode,
  getAllParentNodeId,
  getParentId,
  setCurrentKey
});
</script>

<style lang="scss" scoped>
.folder-icon {
  display: inline-block;
  vertical-align: middle;
}

.tree-icon-container {
  .tree-icon {
    display: inline-block;
    margin: 8px 0 0 8px;
    font-size: 12px;
  }
}

:deep(.px-tree-node__content) {
  width: 100%;
}

.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;

  .text {
    max-width: 120px;
    overflow: hidden; /* 溢出内容隐藏 */
    text-overflow: ellipsis; /* 溢出部分显示省略号 */
    white-space: nowrap; /* 禁止换行 */
  }
}

.show-hide:hover :nth-child(2) {
  display: inline !important;
}
</style>
